package commands;

import java.util.ArrayList;
import java.util.List;

import user.User;
import messages.*;
import core.GameManager;
import core.UserManager;
import event.*;
import game.*;


/**
 * The UserDetails command.
 * 
 * This command will handle UserDetails messages.
 */
public class UserDetailsCommand extends Command {

	
	public UserDetailsCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		GameManager gameManager = this.controller.getGameManager();
		UserManager userManager = this.controller.getUserManager();
		UserDetailsMessage message = (UserDetailsMessage) this.message;
		Player player = null;
		
		synchronized(userManager) {
			if (userManager.isLoginAvailable(message.getLogin())) {
				this.controller.fireInvalidUserDetailsRequestEvent(new InvalidUserDetailsRequestEventArgs(
						user.getLogin(), new InvalidUserDetailsRequestMessage(InvalidUserDetailsRequestMessage.ErrorCode.UnknownUser, message)));
				
				return;
			}
			
			player = userManager.getPlayer(message.getLogin());
		}
		
		List<MatchStatistics> oldMatchs = null;
		List<MatchStatistics> activeMatchs = new ArrayList<MatchStatistics>();
		
		synchronized(gameManager) {
			oldMatchs = gameManager.getOldMatchsByPlayer(player);
			
			for (Match match : gameManager.getActiveMatchsByPlayer(player)) {
				activeMatchs.add(new MatchStatistics(match));
			}
		}
			
		UserDetailsReplyMessage replyMsg = new UserDetailsReplyMessage(player, oldMatchs, activeMatchs);	
						
		// Fires the UserDetails event.
		this.controller.fireUserDetailsReplyEvent(new UserDetailsReplyEventArgs(this.user.getLogin(), replyMsg));
	}
}
